/**
 */
;
(function(){
'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('AgreementDetailCtrl', ['$scope','InsuranceService','CommunityService','$http','$upload','$state', 'AgreementService','$location','$stateParams','BaseURL','Modal',
	    function ($scope,InsuranceService,CommunityService,$http,$upload,$state,agreementService,$location,$stateParams,baseUrl,Modal) {
            $scope.agreementDetail={};
		$scope.communityService = CommunityService;
		 CommunityService.getBaseCode('{codeType:\'agreementType\'}');
		 CommunityService.getBaseCode('{codeType:\'areas\'}');
		CommunityService.initCodeListDatas();
		 agreementService.queryPayment().success(function(res){
			 $scope.paymentModeList = res;
		 });
			InsuranceService.initMedicalOrgInfoList().success(function(response){
	            $scope.medicalOrgInfoList = response.medicalOrgList;
			});
	     $scope.UrlParams = $stateParams;
			// 表头以及json对应的属性名称

            $scope.columns = [
                {label:'序号',map:'index',width:'30%'},
                {label:'文件名称',map:'name',width:'40%'},
                {label:'操作',width:'30%',
                    cellTemplate:'<td><a ng-click="downLoadFile(data)" >下载</a>     ' +
                        '<a ng-click="openLoadFile(data)" >查看</a></td>'
                }
            ];
            $scope.path="";
            var params = {id:$scope.UrlParams.providerid};
            $scope.onSubmit = function(){
	            agreementService.show(params).success(function(res){
                    $scope.agreementDetail = res.result;
                    $scope.path=res.path;
                    checkedPayModes($scope.agreementDetail.payMentMode);
				});
                imageList();
	        };

	        $scope.inputChange = function(){
			      if($scope.agreementDetail.dateAgreementEff>$scope.agreementDetail.dateAgreementEnd)
		            {
		                Modal.alert('协议终止日期不得早于协议生效日期！');
		                return;
			          }
	        }
            function imageList()
            {
                agreementService.showImage(params).success(function(res){
                    $scope.tableData=res.result.imgList;
                });
            }
            /**
             * 下载文件
             */
            $scope.downLoadFile=function(item){
                var path="";
                var suffix = item.name.substring(0,item.name.lastIndexOf('.'));
                window.location = baseUrl + 'agreement/downloadFile.do?fileInfoId='+item.businessNo+'/insurance/'+suffix+
                    '&fileName='+item.name+'&path='+path;
            }
            /**
             * 查看文件
             */
            $scope.openLoadFile=function(item){
                var path= $scope.path+'/'+item.businessNo+'/insurance/'+ item.name;

               var  param={filePath:path};
                $http.post(baseUrl + 'agreement/exitFile.do',param).success(function(data) {
                    if(data.state!="error")
                    {
                        window.open(baseUrl + '/file/openPdfFile.do?filePath='+path);
                    }else
                    {
                        Modal.alert(data.msg);
                    }
                })

            }
            /**
             * 选中支付方式
             * @param payMentMode
             */
            function checkedPayModes(payMentMode) {
                var payModes = payMentMode.split(',');
                if(payMentMode.indexOf(',')>0)
                {
                    angular.forEach(payModes ,function(payMode,index){
                        angular.forEach($scope.paymentModeList ,function(data,index){
                            if (payMode == data.codeno) {
                                data.checked = true;
                            }
                        });
                    });
                }else
                {
                    angular.forEach($scope.paymentModeList ,function(data,index){
                        if (payMentMode == data.codeno) {
                            data.checked = true;
                        }
                    });
                }
            }

            /**
             * 保存
             * @param payMentMode
             */

            $scope.updateAgreement = function() {
                var payMode = [];
                angular.forEach($scope.paymentModeList ,function(data,index){
                    if (data.checked === true) {
                        payMode.push(data.codeno);
                    }
                });
                $scope.agreementDetail.payMentMode = payMode.join(",");
                  if(check())
                  {
                    $http.post(baseUrl + 'agreement/update.do',$scope.agreementDetail).success(function(data) {
                        if(data.state=='0')
                        {
                            Modal.alert(data.msg);
                            $state.go('agreement.agreementBase');
                        }else
                        {
                            Modal.alert("修改失败！");
                        }
                    })
                  }
            }
            function check()
            {
            	
            	var dateReg =/^\d{4}-\d{2}-\d{2}$/; 
                if(!$scope.agreementDetail.agreementNo)
                {
                    Modal.alert('协议编号为必填项！');
                    return false;
                }else  if(!$scope.agreementDetail.idHealthcareProvider)
                {
                    Modal.alert('医疗机构名称为必填项！');
                    return false;
                }else  if(!$scope.agreementDetail.organizationType)
                {
                    Modal.alert('卫生机构类别为必填项！');
                    return false;
                }else  if(!$scope.agreementDetail.agreementType)
                {
                    Modal.alert('协议类型为必填项！');
                    return false;
                }else  if($scope.agreementDetail.dateAgreementEff>$scope.agreementDetail.dateAgreementEnd)
                {
                    Modal.alert('协议终止日期不得早于协议生效日期！');
                    return false;
                }else  if(!dateReg.test($scope.agreementDetail.dateAgreementEff))
                {
                    Modal.alert('协议生效日期为必填项,并且必须输入正确的日期格式(yyyy-MM-dd)！');
                    return false;
                }else  if(!dateReg.test($scope.agreementDetail.dateAgreementEnd))
                {
                    Modal.alert('协议终止日期为必填项,并且必须输入正确的日期格式(yyyy-MM-dd)！');
                    return false;
                }else  if(!$scope.agreementDetail.regionCode)
                {
                    Modal.alert('统筹区域为必填项！');
                    return false;
                }else  if(!$scope.agreementDetail.payMentMode)
                {
                    Modal.alert('支付方式为必填项！');
                    return false;
                }
                else
                {
                    return true;
                }
            }
            /**
             * 取消
             */
            $scope.goList = function () {
                $state.go("agreement.agreementBase");
            };

            /**
            * 设置支付方式
            */
            $scope.setPaymentMode = function(data){
                if (data.checked === true) {
                    data.checked = false;
                }
                else {
                    data.checked = true;
                }
            }
            $scope.checkRows = [];

            function findCheck(d) {
                for(var i=0;i< $scope.checkRows .length;i++) {
                    var checkedData =  $scope.checkRows [i];
                    if(checkedData.itemId == d.itemId) {
                        return i;
                    }
                }
                return -1;
            }

            $scope.$on('fwatable.checked', function(e,d){
                if(findCheck(d) == -1) {
                    $scope.checkRows .push(d);
                }
            });

            $scope.$on('fwatable.unchecked', function(e,d){
                var index = findCheck(d);
                if(index != -1) {
                    $scope.checkRows.splice(index,1);
                }
            });
            
            /**
             * 鼠标移动到div上 显示
             */
            $scope.mouseover = function(data) {
            	data.show = true;
            }
            /**
             * 鼠标移动到div上 隐藏
             */
            $scope.mouseout = function(data) {
            	data.show = false;
            }
            
            /**
             * 文件批量删除
             */
            $scope.deleteFile=function(id)
            {
                    var  params= {
                        id : "'"+id+"'"
                    };
                    Modal.confirm('确认删除吗？',function() {
                        $http.post(baseUrl + 'agreement/deleteFile.do', params).success(function (data) {
                            if (data.state == '0') {
                                Modal.alert("文件删除成功！");
                            } else {
                                Modal.alert("删除失败！");
                            }
                            imageList();
                        })
                    })

            }

            /**
             * 文件上传
             */
            $scope.files=[];
            var fileTypes = ['jpg', 'jpeg', 'png', 'bmp', 'gif', 'txt', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx','pdf', 'csv', 'rar', 'zip','7z', 'cab', 'iso'];
            $scope.uploadFile = function(){
             if($scope.files.length>0)
                 {
                    for(var i = 0; i < $scope.files.length; i++){
                        var file = $scope.files[i];
                        var fileName = file.name;
                        var fileNameArray = fileName.split(".");
                        var fileType = fileNameArray[fileNameArray.length - 1];

                       if(!isBelongToFileTypes(fileTypes, fileType)){
                            Modal.alert("文件格式只支持(jpg、jpeg、bmp、gif、png、txt、doc、docx、xls、xlsx、ppt、pptx、pdf、csv、rar、zip、7z、cab、iso)");
                            return;
                        }
                        if(file.size > 2097152){
                            Modal.alert(fileName + "的大小不能超过2M！");
                            return;
                        }
                   }
                    //防止处理时间过长重复提交，提交按钮禁用
                    $scope.isDisabled=true;

                    $upload.upload({
                        url : baseUrl + 'agreement/imageInfoCreate.do',
                        params : {
                            id : $scope.agreementDetail.id
                        },
                        file : $scope.files
                    }).success(function(data) {
                        $scope.isDisabled=false;
                        if(data.state=='0')
                        {
                            Modal.alert(data.msg);
                            $scope.files=[];
                        }else
                        {
                            Modal.alert("附件上传失败！");
                        }
                      imageList();
                    });
                }else
             {
                 Modal.alert("请选择需上传的附件！");
             }
            }
            function isBelongToFileTypes(fileTypes, fileType)
            {
                for(var i = 0; i < fileTypes.length; i++)
                {
                    var tmpFileType = fileTypes[i];
                    if(tmpFileType == fileType.toLocaleLowerCase())
                    {
                        return true;
                    }
                }

                return false;
            }
            $scope.onSubmit();
	    }
    ]);
})();